package com.zzgc.modules.controller;

import com.alibaba.fastjson.JSON;
import com.zzgc.common.entity.*;
import com.zzgc.common.response.HttpStatus;
import com.zzgc.common.response.Result;
import com.zzgc.common.utils.IdCardNumberMethod;
import com.zzgc.common.utils.StringUtils;
import com.zzgc.modules.async.AsyncStatistical;
import com.zzgc.modules.log.ApiLog;
import com.zzgc.modules.param.AddStudentParam;
import com.zzgc.modules.param.CountyParam;
import com.zzgc.modules.param.GradeParam;
import com.zzgc.modules.param.ImportStudentTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

/**
 * 数据接收类
 * @Author:
 * @CreateTime: 2022-12-17  14:18
 * @Description:
 * @Version: 1.0
 */
@RestController
@RequestMapping("receive")
@ApiLog(value = "数据接收类, 只县级用，不可测试调用", url = "receive")
//@Api(tags = "数据接收类")
public class ReceiveController extends BaseController {

    @PostMapping("students")
    @ApiOperation(value = "接收区县的学生筛查档案数据")
    @ApiLog(value = "接收区县的学生筛查档案数据", url = "students", method = RequestMethod.POST)
    @Transactional
    public Result students(@RequestBody List<StudentArchives> list){
        //list.forEach(System.out::println);
        // 去重集合
        Map<String, StudentArchives> hashMap = new HashMap<>();
        for (StudentArchives archives : list) {
            // 没有就创建，有就不创建
             studentTableDao.addStudentTable(archives.getTableName());
            // 查询是否有之前的旧数据，如果有就更新
            StudentArchives archives1 = archivesService.queryByUniqueIdYearNumber(archives.getSStudentUniqueId(), archives.getSYear(), archives.getSNumber(), archives.getTableName());
            // archive_410000_2022_测试学校_1
            hashMap.put(archives.getTableName()+ "_" + archives.getSSchoolName() + "_" + archives.getSNumber(), archives);
            if (StringUtils.isNotNull(archives1)) { // 如果存在就更新数据
                archives.setId(archives1.getId());
                archivesService.update(archives);
            }else {   // 添加数据
                archivesService.insert(archives);
            }
        }
        // 统计学校筛查人数
        asyncStatistical.updateStudentScreenNum(hashMap);

        return Result.builder()
                .code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase())
                .data(list)
                .build();
    }

    // 暂时不用
    @PostMapping("schools")
    @ApiLog(value = "接收区县的学校和部门的数据同步", url = "schools", method = RequestMethod.POST)
    @ApiOperation(value = "接收区县的学校和部门的数据同步")
    public Result schools(@RequestBody List<AuthUser> users){
        users.forEach(System.out::println);
        return Result.builder()
                .code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase())
                .data(users)
                .build();
    }

    /**
     *  删除学生(省级和区县学生数据做到同步进行，区县删除省级同步删除，删除的人的筛查记录还在)
     *  学校数量数据同步
     * @Author
     * @Description
     * @Date  2023/5/27 11:32
     * @Param
     * @return
     */
    @PostMapping("del/students")
    @ApiLog(value = "删除学生", url = "del/students", method = RequestMethod.POST)
    public Result delStudent(@RequestBody Map<Long, String> map) {
//        System.out.println("studentId = " + map);
        Long schoolId = null;
        boolean flag = true;
        String year = null;
        for (Map.Entry<Long, String> entry : map.entrySet()) {
            Long studentId = entry.getKey();
            year = entry.getValue();
            if (flag){ // 寻找学生所在的学校id
                StudentSchool studentSchool = new StudentSchool();
                studentSchool.setSStudentId(studentId);
                studentSchool.setSYear(year);
                List<StudentSchool> studentSchools = studentSchoolService.queryByPage(studentSchool);
                if (StringUtils.isNotEmpty(studentSchools)) {
                    schoolId = studentSchools.get(0).getSSchoolId();
                    flag = false;
                }
            }
            // 只删除学生学校表，不删除学生原表，保证历年的某个学生还在
            studentSchoolService.deleteByStudentId(studentId, year);
        }
        if (schoolId != null) {
            // 统计学校总人数
            asyncStatistical.updateStudentNum(schoolId, year);
        }
        return Result.builder().code(HttpStatus.OK.value()).msg(HttpStatus.OK.getReasonPhrase())
                .data(map).build();
    }

    /**
     *  添加单个学生
     * @Author
     * @Description
     * @Date  2023/2/2 15:34
     * @Param
     * @return
     */
    @PostMapping("addStudent")
    @ApiLog(value = "接收县级添加单个学生，返回学生唯一id", url = "addStudent", method = RequestMethod.POST)
    @Transactional
    public Result addStudent(@RequestBody @Validated AddStudentParam addStudentParam){
        System.out.println("addStudentParam = " + addStudentParam);
        // 判断是否存在该学生
        List<Student> students = studentService.queryByIdCard(addStudentParam.getSIdCard());
        Student student = new Student();
        if (students.size() > 1) {
            throw new RuntimeException("存在多个相同的身份证号");
        }else if (students.size() == 0){
            // 添加学生
            student.setSIdCard(addStudentParam.getSIdCard());
            student.setSName(addStudentParam.getSName());
            student.setSMobile(addStudentParam.getSMobile());
            student.setSSex(addStudentParam.getSSex());
            student.setSBirthday(addStudentParam.getSBirthday()); // 生日
            student.setSCreateDate(new Date());
            student = studentService.insert(student);
        }else {
            // 存在就用id
            student = students.get(0);
        }

        // 判断是否存在该学校
        School school = schoolService.queryByName(addStudentParam.getSchool().getSName());
        if (school == null){
            School school1 = addStudentParam.getSchool();
            // 添加部门
            AuthDepart authDepart = new AuthDepart();
            authDepart.setARegionId(Long.valueOf(school1.getSArea()));
            authDepart.setALevel(2);
            // 查询父级
            List<AuthDepart> authDeparts = departService.queryByPage(authDepart);
            if (authDeparts.size() < 1) {
                return Result.builder().code(500)
                        .msg("省级不存在该区县单位，请联系管理员创建后重试！").build();
            }
            authDepart.setAParentId(authDeparts.get(0).getId());
            authDepart.setAName(school1.getSName());
            authDepart.setANote(school1.getSName());
            authDepart.setALevel(3);
            // 通过区域编号查询地区
            SysDictItem sysDictItem = sysDictItemService.queryByCode(school1.getSArea());
            SysDict sysDict = sysDictService.queryById(Long.valueOf(sysDictItem.getSDictId()));
            authDepart.setAIdBak(sysDictItem.getSName());
            authDepart.setAParentIdBak(sysDict.getSName());
            authDepart.setACreateDate(new Date());

            AuthDepart insert = departService.insert(authDepart);
            // 添加学校
            school1.setSSchoolDepartId(insert.getId());
            school1.setSDepartId(insert.getAParentId());
            school1.setSCreateDate(new Date());
            school = schoolService.insert(school1);
        }
        // 查询是否有本学校的管理员
        AuthUser user = new AuthUser();
        user.setADepartId(school.getSDepartId());
        user.setASchoolId(school.getId());
        user.setSize(Integer.MAX_VALUE);
        List<AuthUser> authUsers = userService.queryByPage(user);
        if (authUsers.size() < 1) {
            AuthUser user1 = addStudentParam.getUser();
            user1.setId(null);
            user1.setASchoolId(school.getId());
            user1.setADepartId(school.getSDepartId());
            userService.insert(user1); // 添加学校用户
        }

        // 判断是否存在本年的学生
        StudentSchool studentSchool = new StudentSchool();
        studentSchool.setSStudentId(student.getId());
        studentSchool.setSYear(addStudentParam.getSchool().getSYear());
        Long count = studentSchoolService.count(studentSchool);
        if (count > 0) {
            // throw new RuntimeException("已存在" + student.getSName() + "的记录!");
            return Result.builder()
                    .code(HttpStatus.OK.value())
                    .msg(HttpStatus.OK.getReasonPhrase())
                    .data(student.getId())
                    .build();
        }
        studentSchool.setSSchoolId(school.getId());
        studentSchool.setSArea(school.getSArea());
        studentSchool.setSGradeName(addStudentParam.getSGradeName());
        studentSchool.setSClassName(addStudentParam.getSClassName());
        studentSchool.setSStudentNum(addStudentParam.getSStudentNum());

        studentSchool.setSCreateDate(new Date());
        studentSchoolService.insert(studentSchool);
        //addStudentParam.setSStudentId(student.getId());
        // 统计学校总人数
        asyncStatistical.updateStudentNum(school.getId(), addStudentParam.getSchool().getSYear());
        return Result.builder()
                .code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase())
                .data(student.getId())
                .build();
    }

    /**
     *  添加多个学生
     * @Author
     * @Description
     * @Date  2023/2/2 15:34
     * @Param
     * @return
     */
    @PostMapping("addStudents")
    @ApiLog(value = "接收县级添加多个学生记录,返回学生唯一id", url = "addStudents", method = RequestMethod.POST)
    @Transactional
    public Result addStudents(@RequestBody Map<String, Object> map) {
        School school1 = JSON.parseObject(JSON.toJSONString(map.get("school")),School.class);
        List<ImportStudentTemplate> students  = JSON.parseArray(JSON.toJSONString(map.get("students")), ImportStudentTemplate.class) ;
        AuthUser authUser = JSON.parseObject(JSON.toJSONString(map.get("user")), AuthUser.class);
        System.out.println("school = " + school1);
        students.forEach(System.out::println);

        // 判断是否存在该学校
        School school = schoolService.queryByName(school1.getSName());
        if (school == null){
            // 添加部门
            AuthDepart authDepart = new AuthDepart();
            authDepart.setARegionId(Long.valueOf(school1.getSArea()));
            authDepart.setALevel(3);
            // 查询学校所在的区县是否存在
            List<AuthDepart> authDeparts = departService.queryByPage(authDepart);
            if (authDeparts.size() < 1) {
                return Result.builder().code(500)
                        .msg("省级不存在该区县单位，请联系管理员创建后重试！").build();
            }

            authDepart.setAParentId(authDeparts.get(0).getId());
            authDepart.setAName(school1.getSName());
            authDepart.setANote(school1.getSName());
            authDepart.setALevel(4);
            // 通过区域编号查询地区
            SysDictItem sysDictItem = sysDictItemService.queryByCode(school1.getSArea());
            SysDict sysDict = sysDictService.queryById(Long.valueOf(sysDictItem.getSDictId()));
            authDepart.setAIdBak(sysDictItem.getSName());
            authDepart.setAParentIdBak(sysDict.getSName());
            authDepart.setACreateDate(new Date());

            AuthDepart insert = departService.insert(authDepart);
            // 添加学校
            school1.setSSchoolDepartId(insert.getId());
            school1.setSDepartId(insert.getAParentId());
            school1.setSCreateDate(new Date());
            school = schoolService.insert(school1);
        }
        // 查询是否有本学校的管理员
        AuthUser user = new AuthUser();
        user.setADepartId(school.getSSchoolDepartId()); // 学校部门的id
        user.setASchoolId(school.getId());
        user.setSize(Integer.MAX_VALUE);
        List<AuthUser> authUsers = userService.queryByPage(user);
        if (authUsers.size() < 1) {
            authUser.setId(null);
            authUser.setASchoolId(school.getId());
            authUser.setADepartId(school.getSSchoolDepartId()); // 学校部门的id
            userService.insert(authUser); // 添加学校管理员用户
        }

        List<AddStudentParam> list = new ArrayList<>();
        for (ImportStudentTemplate student : students) {
            AddStudentParam addStudentParam = new AddStudentParam();
            addStudentParam.setSStudentNum(student.getSStudentId() + "");
            addStudentParam.setSSex(student.getSSex());
            addStudentParam.setSOkMirror(student.getSOkMirror());
            addStudentParam.setSName(student.getSName());
            addStudentParam.setSMobile(student.getSMobile());
            addStudentParam.setSIdCard(student.getSIdCard());
            addStudentParam.setSGradeName(student.getSGradeName());
            addStudentParam.setSClassName(student.getSClassName());

            // 判断是否存在该学生
            List<Student> studentList = studentService.queryByIdCard(student.getSIdCard());
            Student stu = new Student();
            if (studentList.size() > 1) {
                throw new RuntimeException("存在多个相同的身份证号" + student.getSIdCard());
            }else if (studentList.size() == 0){
                // 添加学生
                stu.setSIdCard(student.getSIdCard());
                stu.setSName(student.getSName());
                stu.setSMobile(student.getSMobile());
                stu.setSSex(student.getSSex());
                try {
                    Date date = IdCardNumberMethod.getBirthDayFromIdCard(student.getSIdCard());
                    stu.setSBirthday(date); // 生日
                    addStudentParam.setSBirthday(date);
                } catch (Exception e) {
                    throw new RuntimeException("识别"+ student.getSName() +"身份证: " + student.getSIdCard() + "获取生日失败!");
                }
                stu.setSCreateDate(new Date());
                stu = studentService.insert(stu);
            }else {
                // 存在就用id
                stu = studentList.get(0);
                addStudentParam.setSBirthday(stu.getSBirthday());
            }

            // 判断是否存在本年的学生
            StudentSchool studentSchool = new StudentSchool();
            studentSchool.setSStudentId(stu.getId());
            studentSchool.setSYear(school1.getSYear());
            Long count = studentSchoolService.count(studentSchool);
            if (count > 0) {
                // throw new RuntimeException("已存在" + student.getSName() + "的记录!");
            }else {
                studentSchool.setSSchoolId(school.getId());
                studentSchool.setSArea(school.getSArea());
                studentSchool.setSGradeName(student.getSGradeName());
                studentSchool.setSClassName(student.getSClassName());
                studentSchool.setSStudentNum(student.getSStudentId() + "");

                studentSchool.setSCreateDate(new Date());
                studentSchoolService.insert(studentSchool);
            }
            addStudentParam.setSStudentId(stu.getId());
            list.add(addStudentParam);
        }
        // 统计学校总人数
        asyncStatistical.updateStudentNum(school.getId(), school1.getSYear());

        return Result.builder().code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase()).data(list).build();
    }

    @PostMapping("allDistrictAnalysis")
    @ApiLog(value = "接收县级的可视化分析汇总", url = "allDistrictAnalysis", method = RequestMethod.POST)
    public Result allDistrictAnalysis(@RequestBody List<CountyParam> countyParams) {
        if (StringUtils.isEmpty(countyParams)) {
            return Result.builder().code(500).msg("传输数据为空").build();
        }
        // countyName=郑州市金水区教育局_20221,  区域名字，学年，筛查次数，城市，区县
        // count=415, 总人数
        // inspect=4, 筛查人数
        // coverage=1.0, 覆盖率
        // unhealthy=75.0, 视力不良率
        // myopiaRate=25.0, 近视率
        // manCount=3, 男生人数
        // manMyopiaNum=1, 男生近视人数
        // manMyopiaRate=33.3, 男生近视率
        // womanCount=1, 女生人数
        // womanMyopiaNum=0, 女生近视人数
        // womanMyopiaRate=0.0, 女生近视率
        // abnormalVision=3, 视力不良人数
        // myopia=1, 近视人数
        for (CountyParam countyParam : countyParams) {
            // 郑州市金水区教育局_2022_4
            String[] s = countyParam.getCountyName().split("_");
            AuthDepart authDepart = departService.queryByPage(s[0]); // 查询市级和省级
            // 判断是否存在现有数据
            StaticDistrictVisualization visualization = new StaticDistrictVisualization();
            visualization.setYear(s[1]);
            visualization.setNumber(Integer.valueOf(s[2]));
            visualization.setDistrictName(s[0]);
            List<StaticDistrictVisualization> visualizations = districtVisualizationService.queryByPage(visualization);
            // 设置数据
            visualization.setCity(authDepart.getAParentIdBak());
            visualization.setDistrict(authDepart.getAIdBak());
            visualization.setCount(countyParam.getCount());
            visualization.setInspect(countyParam.getInspect());
            visualization.setCoverage(countyParam.getCoverage() + "");
            visualization.setUnhealthy(countyParam.getUnhealthy() + "");
            visualization.setMyopiaRate(countyParam.getMyopiaRate() + "");
            visualization.setManCount(countyParam.getManCount());
            visualization.setManMyopiaNum(countyParam.getManMyopiaNum());
            visualization.setManMyopiaRate(countyParam.getManMyopiaRate() + "");
            visualization.setWomanCount(countyParam.getWomanCount());
            visualization.setWomanMyopiaNum(countyParam.getWomanMyopiaNum());
            visualization.setWomanMyopiaRate(countyParam.getWomanMyopiaRate() + "");
            visualization.setAbnormalVision(countyParam.getAbnormalVision());
            visualization.setMyopia(countyParam.getMyopia());
            if (StringUtils.isNotEmpty(visualizations)) { // 如果存在数据就更新
                Long id = visualizations.get(0).getId();
                visualization.setId(id);
                visualization.setUpdateTime(new Date());
                districtVisualizationService.update(visualization);
            }else {
                visualization.setCreateTime(new Date());
                districtVisualizationService.insert(visualization);
            }
        }
        // 异步调用统计市级，省级可视化数据
        asyncStatistical.updateCityAnalysis();
        countyParams.forEach(System.out::println);
        return Result.builder().code(HttpStatus.OK.value())
                .msg(HttpStatus.OK.getReasonPhrase()).data(countyParams).build();
    }

    @PostMapping("allGradeAnalysis")
    @ApiLog(value = "接收县级的各年级的可视化分析汇总", url = "allGradeAnalysis", method = RequestMethod.POST)
    public Result allGradeAnalysis(@RequestBody List<GradeParam> gradeParams) {
        if (StringUtils.isEmpty(gradeParams)) {
            return Result.builder().code(500).msg("传输数据为空").build();
        }
        gradeParams.forEach(System.out::println);
        // countyName=410105_2022_1_初中_郑州市管城测试中学_二年级,  区域代码，学年，筛查次数，学校类型，学校名字，年级
        // count=415, 总人数
        // inspect=4, 筛查人数
        // coverage=1.0, 覆盖率
        // unhealthy=75.0, 视力不良率
        // myopiaRate=25.0, 近视率
        // abnormalVision=3, 视力不良人数
        // myopia=1, 近视人数
        for (GradeParam gradeParam : gradeParams) {
            String[] split = gradeParam.getGradeName().split("_");
            SysDictItem sysDictItem = sysDictItemService.queryByCode(split[0]); // 区县
            SysDict sysDict = sysDictService.queryById(Long.valueOf(sysDictItem.getSDictId())); // 市级
            // 查询是否存在现有数据
            StaticSchoolVisualization visualization = new StaticSchoolVisualization();
            visualization.setYear(split[1]);
            visualization.setNumber(Integer.valueOf(split[2]));
            visualization.setDistrict(sysDictItem.getSName());
            visualization.setType(split[3]);
            visualization.setSchoolName(split[4]);
            visualization.setClassName(split[5]);
            List<StaticSchoolVisualization> schools = schoolVisualizationService.queryByPage(visualization);
            // 设置数据
            visualization.setCity(sysDict.getSName());
            visualization.setCount(gradeParam.getCount());
            visualization.setInspect(gradeParam.getInspect());
            visualization.setCoverage(gradeParam.getCoverage() +"");
            visualization.setAbnormalVision(gradeParam.getAbnormalVision());
            visualization.setUnhealthy(gradeParam.getUnhealthy() + "");
            visualization.setMyopia(gradeParam.getMyopia());
            visualization.setMyopiaRate(gradeParam.getMyopiaRate() +"");
            if (StringUtils.isNotEmpty(schools)) { // 不会空就更新
                visualization.setId(schools.get(0).getId());
                visualization.setUpdateTime(new Date());
                schoolVisualizationService.update(visualization);
            }else { // 为空就创建
                visualization.setCreateTime(new Date());
                schoolVisualizationService.insert(visualization);
            }

        }
        return Result.builder().build();
    }

}
